# -*- coding: utf-8 -*-

# __date:       2021/7/12
# __author:     Yang Chao
# __function:

class Solution:
    def threeSumClosest1(self, nums: List[int], target: int) -> int:
        """
        解法一：类似于三数之和，双指针遍历
            首先将数组排序
            然后扫描nums，确定第一个元素值，然后将第二个指针和第三个指针分别作为l, r进行双指针遍历
                如果当前元素和前一个元素相等，为了避免重复，这个节点需要丢弃
                如果当前累计和和target相等，则直接返回target即可，相等即为距离最小的情况
                如果当前累计和小于target，则向右移动左指针l，同时进行去重操作，更新res
                如果当前累计和大于target，则向左移动右指针r，同时进行去重操作，更新res
            返回res
        :param nums:
        :param target:
        :return:
        """
        res, m, diff = 0, len(nums), float('inf')
        nums.sort()
        for i in range(m):
            if i > 0 and nums[i] == nums[i - 1]:
                continue
            l, r = i + 1, m - 1
            while l < r:
                temp = nums[i] + nums[l] + nums[r]
                if temp == target:
                    return temp
                if temp > target:
                    r -= 1
                    if abs(temp - target) < diff:
                        diff = abs(temp - target)
                        res = temp
                    while l < r and nums[r] == nums[r + 1]:
                        r -= 1
                else:
                    l += 1
                    if abs(temp - target) < diff:
                        diff = abs(temp - target)
                        res = temp
                    while l < r and nums[l] == nums[l - 1]:
                        l += 1
        return res